<template>
  <div class="app-container org">
    <el-card class="leftCard">
      <!-- 搜索条件盒子 -->
      <div>
        <p class="pinformation">搜索条件</p>
        <el-form :model="queryParams" @submit.native.prevent>
          <el-row>
            <el-col :span="15">
              <el-form-item label="部门名称：" prop="deptName">
                <el-input clearable placeholder="请输入部门名称" v-model="queryParams.deptName" maxlength="100"
                  @keyup.enter="handleQuery" />
              </el-form-item>
            </el-col>
            <el-col :span="9">
              <el-row justify="end">
                <el-button type="success" @click="handleQuery">搜索</el-button>
                <el-button class="business resetBtn" @click="resetQuery">重置</el-button>
              </el-row>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 机构列表盒子 -->
      <div>
        <el-row style="justify-content: space-between">
          <el-row>
            <p class="pinformation">部门列表</p>
            <p class="totalStyle">共 {{ total }} 条数据</p>
          </el-row>
          <el-row style="padding-bottom: 5px">
            <el-button type="success" link icon="Plus" @click="addOrgId">新增</el-button>
          </el-row>
        </el-row>
        <el-table class="business" ref="mainTableRef" v-loading="loading" :row-class-name="tableRowClass" :data="deptList"
          @row-click="rowClick" row-key="deptId" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          check-strictly>
          <el-table-column label="部门名称" width="270" prop="deptName" />
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button link type="success" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <el-card class="rightCard">
      <!-- 基础信息 -->
      <el-form label-width="90px" :model="form" :rules="rules" ref="deptRef">
        <div>
          <el-row style="margin-bottom: 5px">
            <el-col :span="22">
              <p class="pinformation">基础信息</p>
            </el-col>
            <el-col :span="2">
              <el-button type="success" size="small" @click="submitForm">保存</el-button>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="部门名称：" prop="deptName">
                <el-input placeholder="请输入部门名称" v-model="form.deptName" clearable maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="上级部门：" prop="parentId">
                <el-tree-select v-model="form.parentId" clearable :data="deptOptions" :props="{
                  value: 'deptId',
                  label: 'deptName',
                  children: 'children',
                }" value-key="deptId" placeholder="选择上级部门" check-strictly />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              <el-form-item label="部门电话：" prop="phone">
                <el-input placeholder="请输入部门电话" v-model="form.phone" clearable maxlength="100" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="部门状态：">
                <el-select placeholder="选择状态" clearable v-model="form.status" style="width:100%">
                  <el-option v-for="item in condition" :key="item.status" :label="item.name" :value="item.status" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="显示顺序：" prop="orderNum">
                <el-input-number v-model="form.orderNum" controls-position="right" :min="0" maxlength="100" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="部门介绍：" prop="remark">
            <el-input type="textarea" maxlength="500" show-word-limit clearable placeholder="请输入部门介绍"
              v-model="form.remark" />
          </el-form-item>
        </div>
      </el-form>
      <!-- 部门人员列表 -->
      <div>
        <div>
          <el-row>
            <p class="pinformation">部门人员列表</p>
            <p class="totalStyle">共 {{ form.sysUserList.length }} 条数据</p>
          </el-row>
        </div>
        <el-table :data="form.sysUserList" v-loading="zsLoading" ref="subTableRef" class="business"
          style="margin-bottom: 10px">
          <el-table-column label="姓名" align="center" prop="nickName" show-overflow-tooltip width="120" />
          <el-table-column label="联系电话" align="center" prop="phonenumber" show-overflow-tooltip width="120" />
          <el-table-column label="岗位/角色" align="center" prop="roleNames" show-overflow-tooltip />
          <el-table-column label="职称" align="center" prop="zcName" show-overflow-tooltip width="80" />
          <el-table-column label="员工编号" align="center" prop="userCode" show-overflow-tooltip />
          <el-table-column label="政治面貌" align="center" prop="zzmlName" show-overflow-tooltip width="80" />
          <el-table-column label="当前状态" align="center" prop="workStatus" show-overflow-tooltip width="80">
            <template #default="scope">
              <span v-if="scope.row.workStatus == 0">正常</span>
              <span v-if="scope.row.workStatus == 1">作废</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" type="index">
            <template #default="scope">
              <el-button link type="success" icon="View" @click="handleUserListView(scope.row)">查看详情</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 部门文件列表 -->
      <div>
        <div>
          <el-row>
            <p class="pinformation">部门文件</p>
            <p class="totalStyle">
              共 {{ form.sysDeptFileList.length }} 条数据
            </p>
            <el-row style="margin-bottom: 5px; margin-left: 20px">
              <el-button type="success" link icon="Plus" @click="handleAdd">新增</el-button>
            </el-row>
          </el-row>
        </div>
        <el-table :data="form.sysDeptFileList" v-loading="zsLoading" ref="subFileTableRef" class="business">
          <el-table-column label="文件名称" align="center" prop="fileName" />
          <el-table-column label="文件编号" align="center" prop="fileCode" />
          <el-table-column label="当前状态" align="center" prop="status" width="80">
            <template #default="scope">
              <span v-if="scope.row.status == 0">正常</span>
              <span v-if="scope.row.status == 1">作废</span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" type="index" width="220">
            <template #default="scope">
              <el-button link icon="View" @click="handleListView(scope.row)">查看</el-button>
              <el-button link icon="EditPen" @click="handleLisEditor(scope.row, scope.$index)">编辑</el-button>
              <el-button link icon="Delete" @click="handleListDelete(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 新增修改弹出框 -->
    <el-dialog :class="'el-dialog-theme3'" append-to-body draggable v-model="userOpen"
      :close-on-click-modal="false">
      <el-form label-width="85px" :model="sysUserForm" :disabled="disabled">
        <el-form-item label="姓名：" prop="nickName">
          <el-input clearable placeholder="请输入姓名" v-model="sysUserForm.nickName" maxlength="100" />
        </el-form-item>

        <el-form-item label="联系电话：" prop="phonenumber">
          <el-input clearable placeholder="请输入联系电话" v-model="sysUserForm.phonenumber" maxlength="100" />
        </el-form-item>

        <el-form-item label="岗位角色：" prop="roles">
          <el-input clearable placeholder="请输入岗位角色" v-model="sysUserForm.roles" maxlength="100" />
        </el-form-item>

        <el-form-item label="职称：" prop="zc">
          <el-input clearable placeholder="请输入职称" v-model="sysUserForm.zc" maxlength="100" />
        </el-form-item>

        <el-form-item label="员工编号：" prop="userCode">
          <el-input clearable placeholder="请输入员工编号" v-model="sysUserForm.userCode" maxlength="100" />
        </el-form-item>

        <el-form-item label="政治面貌：" prop="zzmlName">
          <el-input clearable placeholder="请输入政治面貌" v-model="sysUserForm.zzmlName" maxlength="100" />
        </el-form-item>

        <el-form-item label="当前状态：" prop="workStatus">
          <el-select placeholder="选择状态" clearable v-model="sysUserForm.workStatus">
            <el-option v-for="item in condition1" :key="item.status" :label="item.name" :value="item.status" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="Cancel1" type="danger">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog :class="'el-dialog-theme3'" v-model="open" :title="title" append-to-body draggable
      :close-on-click-modal="false">
      <el-form label-width="85px" :model="sysUserFlieForm" :disabled="disabled" :rules="listrules" ref="listRef">
        <el-form-item label="文件名称：" prop="fileName">
          <el-input clearable placeholder="请输入文件名称" v-model="sysUserFlieForm.fileName" maxlength="100" />
        </el-form-item>

        <el-form-item label="文件编号：" prop="fileCode">
          <el-input clearable placeholder="请输入文件编号" v-model="sysUserFlieForm.fileCode" maxlength="100" />
        </el-form-item>
        <el-form-item label="当前状态：" prop="fileCode">
          <el-select placeholder="选择状态" clearable v-model="sysUserFlieForm.status">
            <el-option v-for="item in condition1" :key="item.status" :label="item.name" :value="item.status" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="success" @click="sava">保存</el-button>
          <el-button @click="Cancel" type="danger">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Dept">
import {
  listDept,
  getDept,
  delDept,
  addDept,
  updateDept,
  listDeptExcludeChild,
} from "@/api/system/dept";
import { getSeqId } from "@/api/common";

const { proxy } = getCurrentInstance();

const open = ref(false);
const title = ref("");
const deptList = ref([]);
const total = ref(0);
const disabled = ref(false);
const highlightRow = ref(true);
const userOpen = ref(false);

// 部门
const deptOptions = ref([]);
const sysUserFlieForm = ref({});
const sysUserForm = ref({});
const loading = ref(true);
const zsLoading = ref(false);

const condition = ref([
  { name: "正常", status: "0" },
  { name: "停用", status: "1" },
]);
const condition1 = ref([
  { name: "正常", status: 0 },
  { name: "作废", status: 1 },
]);

const data = reactive({
  form: {
    status: "0",
    orderNum: 0,
    sysDeptFileList: [],
    sysUserList: [],
  },
  queryParams: {},
  rules: {
    deptName: [
      { required: true, message: "部门名称不能为空", trigger: "blur" },
    ],
  },
  listrules: {
    fileName: [
      { required: true, message: "文件名称不能为空", trigger: "blur" },
    ],
  },
});

const { queryParams, form, rules, listrules } = toRefs(data);

function handleAdd() {
  disabled.value = false;
  sysUserFlieForm.value = { status: 0 };
  open.value = true;
  title.value = "新增/编辑部门文件";
  if (proxy.$refs["listRef"]) {
    proxy.$refs["listRef"].clearValidate();
  }
}

function getList() {
  loading.value = true;
  listDept(queryParams.value).then((res) => {
    total.value = res.data.length;
    deptList.value = proxy.handleTree(res.data, "deptId");
    loading.value = false;
  });
}

function submitForm() {
  proxy.$refs["deptRef"].validate((valid) => {
    if (valid) {
      form.value.status = form.value.status;
      if (form.value.deptId != undefined) {
        updateDept(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addDept(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          form.value.deptId = response.data;
          heightBright.value = response.data;
          open.value = false;
          getList();
        });
      }
    }
  });
}

function handleDelete(row) {
  proxy.$modal
    .confirm("删除部门将删除该部门下的所有数据，确定删除吗? 确定后删除；")
    .then(function () {
      return delDept(row.deptId);
    })
    .then(() => {
      addOrgId();
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function reset() {
  queryParams.value = {
    deptName: null,
  };
}

function resetQuery() {
  reset();
  handleQuery();
}

function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

function addOrgId() {
  zsLoading.value = false;
  reset();
  heightBright.value = "";
  proxy.$refs["deptRef"].clearValidate();
  if (proxy.$refs["listRef"]) {
    proxy.$refs["listRef"].clearValidate();
  }
  form.value = {};
  form.value.sysDeptFileList = [];
  form.value.sysUserList = [];
  getTreeChild();
}

function sava() {
  proxy.$refs["listRef"].validate((valid) => {
    if (valid) {
      if (!sysUserFlieForm.value.id) {
        getSeqId().then((res) => {
          sysUserFlieForm.value.id = res.data;
          form.value.sysDeptFileList.push(
            JSON.parse(JSON.stringify(sysUserFlieForm.value))
          );
        });
      } else {
        form.value.sysDeptFileList[sysUserFlieForm.value.index] =
          sysUserFlieForm.value;
      }
      open.value = false;
    }
  });
}

function Cancel() {
  open.value = false;
}
function Cancel1() {
  userOpen.value = false;
}

function handleListDelete(row) {
  disabled.value = false;
  proxy.$modal
    .confirm("是否确认该条删除数据项？")
    .then(function () {
      form.value.sysDeptFileList.splice(row, 1);
    })
    .then(() => {
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

function handleLisEditor(row, index) {
  proxy.$refs["listRef"].clearValidate();
  disabled.value = false;
  form.value.sysDeptFileList[index] = JSON.parse(JSON.stringify(row));
  open.value = true;
  sysUserFlieForm.value = row;
  sysUserFlieForm.value.index = index;
}

function handleListView(row) {
  proxy.$refs["listRef"].clearValidate();
  disabled.value = true;
  open.value = true;
  sysUserFlieForm.value = row;
}

function rowClick(row) {
  proxy.$refs["deptRef"].clearValidate();
  zsLoading.value = true;
  listDeptExcludeChild(row.deptId).then((response) => {
    deptOptions.value = proxy.handleTree(response.data, "deptId");
  });
  getDept(row.deptId).then((res) => {
    form.value = res.data;
    heightBright.value = row.deptId;
    if (form.value.parentId == 0) {
      delete form.value.parentId;
    }
    zsLoading.value = false;
  });
}

function handleUserListView(row) {
  disabled.value = true;
  userOpen.value = true;
  sysUserForm.value = row;
}

function getTreeChild() {
  listDept().then((response) => {
    deptOptions.value = proxy.handleTree(response.data, "deptId");
  });
}
getTreeChild();
getList();

const heightParams = ref([
  { tableName: "main", bottomHeight: 21 },
  { tableName: "sub", bottomHeight: 300 },
  { tableName: "subFile", bottomHeight: 21 },
]);
function getTableHeight() {
  proxy.adaptiveHeight(proxy, heightParams.value);
}
onMounted(() => {
  nextTick(() => {
    getTableHeight();
    window.addEventListener("resize", getTableHeight);
  })
})
onUpdated(() => {
  nextTick(function () {
    getTableHeight();
  });
});
onBeforeUnmount(() => {
  window.removeEventListener("resize", getTableHeight);
});

const heightBright = ref("");
function tableRowClass({ row }) {
  if (row) {
    if (row.deptId == heightBright.value) {
      return "current-row";
    }
    return "";
  }
}
</script>

<style></style>
